package com.itheima79.googleplay.ui.fragment;

import java.util.ArrayList;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.itheima79.googleplay.R;
import com.itheima79.googleplay.adapter.BasicAdapter;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListView;

public abstract class BaseListFragment<T> extends BaseFragment implements OnItemClickListener{
	protected PullToRefreshListView refreshListView;// 下拉刷新ListView
	protected ListView listView;
	protected BasicAdapter<T> adapter;
	protected ArrayList<T> list = new ArrayList<T>();//集合
	@Override
	protected View getSuccessView() {
		refreshListView = (PullToRefreshListView) View.inflate(getActivity(),
				R.layout.ptr_listview, null);
		// 1.设置刷新模式
		setRefreshMode();
		// 2.设置刷新监听器
		refreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			/**
			 * 下拉刷新和上拉加载更多都会执行该方法，
			 * @param refreshView
			 */
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// 直接调用
				loadingPage.loadDataAndRefreshPage();
			}
		});
		//3.获取PullToRefreshListView内部包裹的ListView
		listView = refreshListView.getRefreshableView();
		setListView();
		//4.添加头部
		addHeader();
		//5.填充数据
		adapter = getAdapter();//需要动态获取一个adapter
		listView.setAdapter(adapter);
		
		//6.设置条目点击监听
		listView.setOnItemClickListener(this);

		return refreshListView;
	}

	/**
	 * 设置刷新模式,父类默认实现是两边都可以刷新，子类可以重写
	 */
	protected void setRefreshMode() {
		refreshListView.setMode(Mode.BOTH);// 设置既可以上拉也可以下拉
	}
	/**
	 * 设置ListView的divider和selector
	 */
	protected void setListView(){
		listView.setDividerHeight(0);//去掉分割线
		listView.setSelector(android.R.color.transparent);//将listveiw的selector设置为透明
	}
	/**
	 * 添加头部的方法，如果子类需要那么可以重新
	 */
	protected void addHeader(){
	}
	/**
	 * 获取adapter
	 * @return
	 */
	protected abstract BasicAdapter<T> getAdapter();
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
	}
	/**
 	 * 检查如果是下拉刷新，则清空集合
 	 */
	public void checkPullFromStart() {
		//1.获取数据
 		if(refreshListView.getCurrentMode()==Mode.PULL_FROM_START){
 			//下拉刷新应该请求第0页的数据
 			list.clear();//清空集合中的数据
 		}
	}
	@Override
	protected Object requestData() {
		return null;
	}

}
